<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>高德地图地点搜索与实时标注</title>
        <script type="text/javascript" src="../internal.js"></script>
        <style>
            #container {
                width: 100%;
                height: 100vh;
            }

            #search-container {
                position: absolute;
                top: 10px;
                left: 10px;
                z-index: 1;
                background: white;
                padding: 10px;
                border-radius: 5px;
                box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
                width: 320px;
            }

            #search-input {
                width: 100%;
                padding: 10px;
                border: 1px solid #ddd;
                border-radius: 4px;
                box-sizing: border-box;
                font-size: 14px;
            }

            #search-results {
                max-height: 300px;
                overflow-y: auto;
                margin-top: 8px;
                display: none;
                border: 1px solid #eee;
                border-radius: 4px;
            }

            .result-item {
                padding: 10px;
                border-bottom: 1px solid #f0f0f0;
                cursor: pointer;
                transition: background-color 0.2s;
            }

            .result-item:hover {
                background-color: #f8f8f8;
            }

            .result-item:last-child {
                border-bottom: none;
            }

            .result-name {
                font-weight: bold;
                font-size: 14px;
                color: #333;
            }

            .result-address {
                color: #666;
                font-size: 12px;
                margin-top: 3px;
            }

            .marker-info {
                padding: 10px;
                min-width: 200px;
            }

            .marker-info h4 {
                margin: 0 0 8px 0;
                color: #1E90FF;
            }

            .marker-info p {
                margin: 5px 0;
                font-size: 13px;
                color: #555;
            }
        </style>
    </head>
    <body>
        <div id="container" style="width:800px;height:800px;"></div>
        <div id="search-container">
            <input id="search-input" type="text" placeholder="输入地点名称（如：天安门、北京大学）">
            <div id="search-results"></div>
        </div>
        <script type="text/javascript" src="../internal.js"></script>
       <script type="text/javascript">
           window._AMapSecurityConfig = {
               securityJsCode: "a913bebad8b9e7480a6d20671d6590a1",
           };
       </script>
       <script src="https://webapi.amap.com/maps?v=2.0&key=9dcdaecbb5705729497da6a268db0f1e"></script>
<!--       <script src="https://webapi.amap.com/subway?v=1.0&key=7c38484365088e3f14d5b41bb32dd374&callback=cbk">
       </script> -->
       <script>
            // 初始化地图
            var map = new AMap.Map('container', {
                zoom: 13,
                center: [116.397428, 39.90923], // 北京天安门
                viewMode: '2D'
            });

            // 创建信息窗口
            var infoWindow = new AMap.InfoWindow({
                offset: new AMap.Pixel(0, -30),
                autoMove: true
            });

            // 存储所有标记
            var markers = [];
            // 存储已添加的地点ID，避免重复添加
            var addedPoiIds = {};
           // 将地点信息插入到UEditor编辑器
           function insertToEditor(poi) {
               // 确保编辑器已初始化

               // 创建要插入的HTML内容
               var htmlContent = `
                           <div style="border: 1px solid #ddd; padding: 10px; margin: 10px 0; border-radius: 4px;">
                               <h3 style="margin-top: 0; color: #1E90FF;">${poi.name}</h3>
                               <p><strong>地址：</strong>${poi.address || '无'}</p>
                               <p><strong>电话：</strong>${poi.tel || '无'}</p>
                               <p><strong>坐标：</strong>经度 ${poi.location.lng.toFixed(6)}, 纬度 ${poi.location.lat.toFixed(6)}</p>
                               <p><img src="https://restapi.amap.com/v3/staticmap?location=${poi.location.lng},${poi.location.lat}&zoom=15&size=600 * 300&markers=mid,,A:${poi.location.lng},${poi.location.lat}&key=9dcdaecbb5705729497da6a268db0f1e" style="max-width: 100%;"></p>
                           </div>
                       `;

               // 执行插入

               editor.execCommand('inserthtml',htmlContent);

               // 滚动到编辑器底部
               editor.setContent( `
                           <div style="border: 1px solid #ddd; padding: 10px; margin: 10px 0; border-radius: 4px;">
                               <h3 style="margin-top: 0; color: #1E90FF;">${poi.name}</h3>
                               <p><strong>地址：</strong>${poi.address || '无'}</p>
                               <p><strong>电话：</strong>${poi.tel || '无'}</p>
                               <p><strong>坐标：</strong>经度 ${poi.location.lng.toFixed(6)}, 纬度 ${poi.location.lat.toFixed(6)}</p>
                               <p><img src="https://restapi.amap.com/v3/staticmap?location=${poi.location.lng},${poi.location.lat}&zoom=10&size=950*500&markers=mid,,A:${poi.location.lng},${poi.location.lat}&key=de212747ea47c12d0f832a2b8f108df8"></p>
                           </div>
                       `);
               editor.focus();
               var range = editor.selection.getRange();
               range.select();
               range.scrollIntoView();
           }
            // 加载所需插件
            AMap.plugin(['AMap.PlaceSearch', 'AMap.AutoComplete'], function() {
                // 地点搜索服务
                var placeSearch = new AMap.PlaceSearch({
                    pageSize: 20,
                    city: '全国',
                    map: map,
                    panel: null
                });

                // 输入提示服务
                var autoComplete = new AMap.AutoComplete({
                    input: 'search-input'
                });

                // 获取DOM元素
                var searchInput = document.getElementById('search-input');
                var searchResults = document.getElementById('search-results');

                // 输入框事件处理
                searchInput.addEventListener('input', function() {
                    if (this.value.trim().length > 1) {
                        autoComplete.search(this.value, function(status, result) {
                            if (status === 'complete' && result.tips && result.tips.length) {
                                showSearchResults(result.tips);
                            } else {
                                hideSearchResults();
                            }
                        });
                    } else {
                        hideSearchResults();
                    }
                });

                // 点击搜索结果项
                searchResults.addEventListener('click', function(e) {
                    var item = e.target.closest('.result-item');
                    if (item) {
                        var tip = JSON.parse(item.dataset.tip);
                        // 执行地点搜索并添加标记
                        searchAndAddMarker(tip.name, tip.adcode || tip.district);
                    }
                });

                // 显示搜索结果列表
                function showSearchResults(tips) {
                    searchResults.innerHTML = '';
                    tips.forEach(function(tip) {
                        // 过滤掉无效的地点建议
                        if (!tip.name || !tip.location) return;

                        var item = document.createElement('div');
                        item.className = 'result-item';
                        item.dataset.tip = JSON.stringify(tip);
                        item.innerHTML = `
                        <div class="result-name">${tip.name}</div>
                        <div class="result-address">${tip.district || ''}${tip.address ? ' · ' + tip.address : ''}</div>
                    `;
                        searchResults.appendChild(item);
                    });

                    if (searchResults.children.length > 0) {
                        searchResults.style.display = 'block';
                    } else {
                        hideSearchResults();
                    }
                }

                // 隐藏搜索结果列表
                function hideSearchResults() {
                    searchResults.style.display = 'none';
                }

                // 搜索地点并添加标记
                function searchAndAddMarker(keyword, city) {
                    searchInput.value = keyword;
                    hideSearchResults();

                    placeSearch.setCity(city || '全国');
                    placeSearch.search(keyword, function(status, result) {
                        if (status === 'complete' && result.poiList && result.poiList.pois) {
                            var pois = result.poiList.pois;

                            // 添加新的标记
                            pois.forEach(function(poi) {
                                if (!addedPoiIds[poi.id]) {
                                    addMarker(poi);
                                    addedPoiIds[poi.id] = true;
                                }
                            });

                            // 调整地图视野以包含所有标记
                            if (pois.length > 0) {
                                map.setFitView();
                            }
                        }
                    });
                }
            });

            // 添加标记函数
            function addMarker(poi) {
                // 创建标记内容
                var markerContent = document.createElement('div');
                markerContent.style.background = '#1E90FF';
                markerContent.style.color = 'white';
                markerContent.style.padding = '4px 8px';
                markerContent.style.borderRadius = '4px';
                markerContent.style.fontSize = '12px';
                markerContent.style.whiteSpace = 'nowrap';
                markerContent.textContent = poi.name.length > 10 ? poi.name.substring(0, 8) + '...' : poi.name;

                // 创建标记
                var marker = new AMap.Marker({
                    position: poi.location,
                    map: map,
                    title: poi.name,
                    content: markerContent,
                    offset: new AMap.Pixel(-15, -15)
                });
                // 标记点击事件 - 直接插入到编辑器
                marker.on('click', function(e) {
                    insertToEditor(poi);
                });
                markers.push(marker);

                // 清除所有标记
                function clearMarkers() {
                    markers.forEach(function(marker) {
                        marker.setMap(null);
                    });
                    markers = [];
                    addedPoiIds = {};
                }

                // 标记点击事件
                marker.on('click', function(e) {
                    var content = `
                    <div class="marker-info">
                        <h4>${poi.name}</h4>
                        <p><strong>地址：</strong>${poi.address || '无'}</p>
                        <p><strong>电话：</strong>${poi.tel || '无'}</p>
                        <p><strong>类型：</strong>${poi.type || '无'}</p>
                    </div>
                `;
                    // 添加插入按钮点击事件
                    content.querySelector('.insert-btn').addEventListener('click', function() {
                        insertToEditor(JSON.parse(this.dataset.poi));
                        infoWindow.close();
                    });
                    editor.execCommand('inserthtml',content);
                    // 滚动到编辑器底部
                    editor.setContent(content);
                    infoWindow.setContent(content);
                    infoWindow.open(map, marker.getPosition());
                });

                markers.push(marker);
            }


            // 点击地图其他地方关闭信息窗口
            map.on('click', function() {
                infoWindow.close();
            });
        </script>
    </body>
</html>
